package com.cskaoyan.demo4.servlet;

import com.cskaoyan.demo4.mapper.MarketBrandMapper;
import com.cskaoyan.demo4.model.MarketBrand;
import com.cskaoyan.demo4.util.JacksonUtil;
import com.cskaoyan.demo4.util.MyBatisUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@WebServlet("/admin/brand/*")
public class AdminBrandServlet extends CommonServlet{
    @SneakyThrows
    public void create(HttpServletRequest request, HttpServletResponse response){
        String jsonStr = request.getReader().readLine();
        //将JSON字符串转换为实例
        MarketBrand marketBrand = JacksonUtil.read(jsonStr, MarketBrand.class);
        marketBrand.setAddTime(new Date());
        marketBrand.setUpdateTime(new Date());
        //插入数据库
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketBrandMapper mapper = sqlSession.getMapper(MarketBrandMapper.class);
        //执行insert、获取自增主键（动态SQL中的最后一块内容-》赋值给的是形参）
        //insert id="insertSelective" //插入语句的标识
        // keyColumn="id" 数据库主键
        // keyProperty="id" Java对象对应的属性（主键）
        // parameterType="com.cskaoyan.demo4.model.MarketBrand" //插入对应的对象（类）
        // useGeneratedKeys="true"> //true、指示MyBatis应该使用JDBC的getGeneratedKeys方法获取自增主键

        mapper.insertSelective(marketBrand);
        System.out.println(marketBrand.getId());

        //关闭资源
        sqlSession.commit();
        sqlSession.close();
    }

    @SneakyThrows
    public void delete(HttpServletRequest request,HttpServletResponse response){
        String jsonStr = request.getReader().readLine();
        MarketBrand marketBrand = JacksonUtil.read(jsonStr, MarketBrand.class);
        //从数据库删除
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketBrandMapper mapper = sqlSession.getMapper(MarketBrandMapper.class);
        int i = mapper.deleteByPrimaryKey(marketBrand.getId());

        sqlSession.commit();
        sqlSession.close();
    }
}
